package com.example.security.security;

import com.example.security.bean.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

public class MyUserDetails implements UserDetails {

  private final User user;

  public MyUserDetails(User user) {
    this.user = user;
  }

  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    // 提供一个方法给框架使用, 用以获取当前这个用户的权限
    // 返回一个GrantedAuthority的集合
    var r = new ArrayList<GrantedAuthority>();

    //    user.getRoles().forEach(e -> r.add(new MyGrantedAuthority(e)));

    user.getRoles()
        .forEach(
            a -> {
              r.add(() -> "ROLE_" + a);
            });

    return r;
  }

  @Override
  public String getPassword() {
    return user.getPassword();
  }

  @Override
  public String getUsername() {
    return user.getName();
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return user.getActivated();
  }
}
